package com.cq.controller;

import com.cq.pojo.File;
import com.cq.pojo.Result;
import com.cq.service.FileService;
import com.cq.utils.FastDFSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @Author: 悠久的苍穹
 * @Date: 2021/1/16 16:55
 * @Description: 文件管理控制层
 * @Version: 1.0
 */
@Controller
public class UploadController {

    @Autowired
    FileService fileService;



    @RequestMapping("/getFile")
    @ResponseBody
    public Result getFile(
            @RequestParam(value = "page") Integer page,
            @RequestParam(value = "limit") Integer limit
    ){
        Result result = new Result();
        List<File> fileList = fileService.getFile(page,limit);
        Integer count = fileService.getCount();
        result.setCode(0);
        result.setCount(count);
        result.setData(fileList);
        return result;
    }

    @RequestMapping("/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file){
        Result result = new Result();
        if(file.isEmpty()){
            result.setCode(500);
            result.setMsg("文件为空");
        }else{
            System.out.println(file);
            String name = file.getOriginalFilename();
            String path = FastDFSUtil.uploadFile(file);
            String url = FastDFSUtil.getWebServerUrl(path);
            System.out.println(url);
            fileService.addFile(url,name);
            result.setCode(200);
            result.setMsg(url);
        }
        return result;
    }

    @DeleteMapping("/delFile/{id}")
    @ResponseBody
    public Result delFile(@PathVariable("id") int id) {
        Result result = new Result();
        int i = fileService.deleteById(id);
        if (i==1){
            result.setCode(200);
        }else {
            result.setCode(500);
        }
        return result;
    }

    @PostMapping("/uploadByWX")
    @ResponseBody
    public String uploadByWX(@RequestParam("file") MultipartFile file){
        String url = "";
        if (file.isEmpty()) {
        }else {
            String name = file.getOriginalFilename();
            String str = FastDFSUtil.uploadFile(file);
            url = FastDFSUtil.getWebServerUrl(str);
            fileService.addFile(url,name);
            System.out.println(url);
        }
        return url;
    }
}
